'use strict';

require('./injected_methods')

const SerialPort = require('serialport')
const MSP = require('./msp')
const FC = require('./fc')
const MSPCodes = require('./msp/MSPCodes')
const MspHelper = require('./msp/MSPHelper')

// 全局变量
global.spInstance = null

const main = async () => {

  const ports = await SerialPort.list()
  console.log('ports: ', ports)
  let port = null
  for (const p of ports) {
    if (/^(Betaflight|STMicroelectronics)/i.test(p.manufacturer)) {
      port = p
      break
    }
  }
  if (port) {
    global.spInstance = new SerialPort(port.path, {
      baudRate: 115200
    })
    global.spInstance.on('data', data => {
      console.log('Data:', data)
      console.log(typeof data)

      MSP.read(data)
    })
    global.spInstance.on('close', () => {
        //global.spInstance.write(Buffer.from('exit\n'))
    })
    global.spInstance.on('open', () => {
      console.info('open SerialPort: ' + port.path)

      FC.resetState();
      const mspHelper = new MspHelper()
      MSP.listen(mspHelper.process_data.bind(mspHelper))

      MSP.send_message(MSPCodes.MSP_API_VERSION, false, false, function () {})

      MSP.send_message(MSPCodes.MSP_ATTITUDE, false, false, () => {

      })
    //   global.spInstance.write([0x23], (err, bw) => {

    //     setTimeout(() => {
    //         global.spInstance.write(Buffer.from('help\n'))
    //     }, 250)
    //   })
    })
  }
}

main()